package com.ray.activiti.controller;


import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ray.activiti.common.Constant;
import com.ray.activiti.common.page.Page;
import com.ray.activiti.common.validate.ValidatorUtils;
import com.ray.activiti.service.ActModelerService;
import com.ray.activiti.service.ExtendActBusinessService;
import com.ray.activiti.service.ExtendActModelerService;
import com.ray.activiti.service.ExtendActNodesetService;
import com.ray.activiti.service.ExtendActNodeuserService;
import com.ray.activiti.table.entity.ExtendActModel;
import com.ray.activiti.table.entity.ExtendActNodeset;
import com.ray.activiti.util.DataGridUtil;
import com.ray.api.service.UcenterApiService;
import com.ray.auth.system.emun.UseStatus;
import com.ray.auth.system.table.entity.Button;
import com.ray.auth.system.table.entity.Role;
import com.ray.auth.system.table.entity.User;
import com.zjhc.flyhong.common.function.exception.BussinessException;
import com.zjhc.flyhong.common.function.operator.LoginUser;
import com.zjhc.flyhong.common.function.operator.PageDto;
import com.zjhc.flyhong.common.web.Result;
import com.zjhc.web.controller.WebController;

/**
 * 类的功能描述.
 * 流程模型相关操作
 * @Auther ray  qray686898@163.com
 * @Date 2017/12/28
 * @代码参考或来自  https://github.com/huangxianyuan/hxyFrame
 */
@Controller
@RequestMapping("act/model")
public class ExtendActModelController extends WebController{
    private Logger log = Logger.getLogger(getClass());

    @Autowired
    ExtendActModelerService extendActModelService;
    @Autowired
    ActModelerService actModelerService;
    @Autowired
    ExtendActNodesetService nodesetService;
    @Autowired
    ExtendActNodeuserService nodeuserService;
    @Autowired
    UcenterApiService ucenterApiService;
    @Autowired
    ExtendActBusinessService businessService;
    
   
    
    /**
     * 列表
     * @param model
     * @param actModelEntity
     * @param request
     * @return
     */
    @RequestMapping("view")
    @RequiresPermissions("act:model:view")
    public ModelAndView view(String menuId,ModelAndView modelAndView, HttpServletRequest request){
    	LoginUser user = getLoginUser();
    	Result<Map<String, List<Button>>>  buttonsResult= ucenterApiService.queryUserButtonsWithMenu(user,menuId);
	  	if(buttonsResult.codeSuccess()){
	  		 modelAndView.addObject("buttons", buttonsResult.getData());
	  	}
	  	modelAndView.setViewName("activiti/model/view");
        return modelAndView;
    }
    
    /**
     * 列表
     * @param model
     * @param actModelEntity
     * @param request
     * @return
     */
    @SuppressWarnings("unchecked")
	@RequestMapping("query")
    @RequiresPermissions("act:model:query")
    @ResponseBody
    public ResponseEntity<Map<String,Object>> query(Model model,ExtendActModel actModelEntity, HttpServletRequest request){
    	 LoginUser user = getLoginUser();
    	 PageDto<ExtendActModel> pageDto= this.createJQPage(request);

    	 int pageNum = pageDto.getPage();//Integer.parseInt(request.getParameter(""));
         Page<ExtendActModel> page = extendActModelService.findPage(actModelEntity, pageNum,user);
         List<ExtendActModel> list = page.getResult();
         for(ExtendActModel actModel :list){
        	 actModel.setBaName(ucenterApiService.queryOrgName(actModel.getBaid()));
        	 actModel.setBapName(ucenterApiService.queryOrgName(actModel.getBapid()));
         } 
    	 pageDto.setRecords(list);
    	 pageDto.setTotal(page.getTotal());
 		return doSuccess(DataGridUtil.dataConvert(pageDto));
    }

    /**
     * 新增
     * @param model
     * @param actModelEntity
     * @param request
     * @return
     */
    @RequestMapping("addView")
    @RequiresPermissions("act:model:add")
    public ModelAndView add(String menuId,ModelAndView modelAndView, HttpServletRequest request){
    	LoginUser user = getLoginUser();
    	Result<Map<String, List<Button>>>  buttonsResult= ucenterApiService.queryUserButtonsWithMenu(user,menuId);
	  	if(buttonsResult.codeSuccess()){
	  		 modelAndView.addObject("buttons", buttonsResult.getData());
	  	}
	  	modelAndView.setViewName("activiti/model/add");
        return modelAndView;
    }  
    
    /**
     * 保存
     * @param model
     * @param businessEntity
     * @return
     */
    @RequestMapping(value = "add",method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("act:model:add")
    public ResponseEntity<Result<Object>> processAdd(Model model , ExtendActModel modelEntity){
    	LoginUser user = getLoginUser();
        ValidatorUtils.validateEntity(modelEntity);
        try{
            String modelId = extendActModelService.save(modelEntity,user);
            if(StringUtils.isEmpty(modelId)){
                return doError("保存失败");
            }else{
                return doSuccess("保存成功");
            }
        } catch (Exception e) {
           log.error(e.getLocalizedMessage());
           return doError("保存异常");
        }
    }
    /**
     * 修改
     * @param model
     * @param actModelEntity
     * @param request
     * @return
     */
    @RequestMapping("editView")
    @RequiresPermissions("act:model:edit")
    public ModelAndView editView(String menuId,String id,ModelAndView modelAndView, HttpServletRequest request){
    	LoginUser user = getLoginUser();
    	Result<Map<String, List<Button>>>  buttonsResult= ucenterApiService.queryUserButtonsWithMenu(user,menuId);
	  	if(buttonsResult.codeSuccess()){
	  		 modelAndView.addObject("buttons", buttonsResult.getData());
	  	}
	  	ExtendActModel actModel = extendActModelService.queryObject(id);
	  	modelAndView.addObject("record", actModel);
	  	modelAndView.setViewName("activiti/model/edit");
        return modelAndView;
    }  
    
    
    /**
     * 更新
     * @param modelEntity
     * @return
     */
    @RequestMapping("edit")
    @ResponseBody
    @RequiresPermissions("act:model:edit")
    public ResponseEntity<Result<Object>> edit(ExtendActModel modelEntity){
    	LoginUser user = getLoginUser();
        int count = extendActModelService.update(modelEntity,user);
        if(count>0){
            return doSuccess("更新"+modelEntity.getName()+"成功!");
        }else {
            return doError("更新"+modelEntity.getName()+"失败!");
        }
    }
    
    
    /**
     * 删除模型
     * @param id
     * @return
     */
    @RequestMapping("delete")
    @ResponseBody
    @RequiresPermissions("act:model:delete")
    public ResponseEntity<Result<Object>> del(String id){
        try {
            int count = extendActModelService.delete(id);
            if(count<1){
                return doError("删除失败!",null);
            }else{
                return doSuccess("删除成功!",null);
            }
        } catch (Exception e) {
            log.error(e.getLocalizedMessage());
            return doError(e.getLocalizedMessage(),null);
        }
    }
    
    /**
     * 选择业务
     * @param model
     * @param actModelEntity
     * @param request
     * @return
     */
    @RequestMapping("businessSelectView")
    public ModelAndView businessSelectView(ModelAndView modelAndView, HttpServletRequest request){
	  	modelAndView.setViewName("activiti/model/businessSelect");
        return modelAndView;
    }
    
    
    
    /**
     * 流程图
     * @param model
     * @param actModelEntity
     * @param request
     * @return
     */
    @RequestMapping("picView")
    @RequiresPermissions("act:model:pic")
    public ResponseEntity<byte[]> picView(String modelId,ModelAndView modelAndView, HttpServletRequest request){
    	  if(StringUtils.isEmpty(modelId)){
              throw new BussinessException(-1,"流程模型id不能为空!");
          } 
    	  HttpHeaders headers = new HttpHeaders();
         headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
         byte[] bytes = actModelerService.showFlowImg(modelId);
         return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.CREATED);
    }  
    
    
    /**
     * 节点设置
     * @param model
     * @param actModelEntity
     * @param request
     * @return
     */
    @RequestMapping("nodeView")
    @RequiresPermissions("act:model:node")
    public ModelAndView nodeView(String menuId,String id,ModelAndView modelAndView, HttpServletRequest request){
    	LoginUser user = getLoginUser();
    	Result<Map<String, List<Button>>>  buttonsResult= ucenterApiService.queryUserButtonsWithMenu(user,menuId);
	  	if(buttonsResult.codeSuccess()){
	  		 modelAndView.addObject("buttons", buttonsResult.getData());
	  	}
	  	modelAndView.addObject("id", id);
	  	modelAndView.setViewName("activiti/model/node");
        return modelAndView;
    }  
    
    
    /**
     * 节点列表
     * @param request
     * @return
     * @throws Exception 
     */
    @SuppressWarnings("unchecked")
	@RequestMapping("nodeQuery")
    @RequiresPermissions("act:model:node")
    @ResponseBody
    public ResponseEntity<Map<String,Object>> nodeQuery(Model model,String modelId, HttpServletRequest request) throws Exception{
    	 //LoginUser user = getLoginUser();
    	 PageDto<Map<String, String>> pageDto= this.createJQPage(request);
    	 List<Map<String, String>> flows = actModelerService.getflows(request.getContextPath(),modelId);
    	 pageDto.setRecords(flows);
 		return doSuccess(DataGridUtil.dataConvert(pageDto));
    }
    
    
    /**
     * 节点详情设置
     * @param request
     * @return
     */
    @RequestMapping("nodeSettingView")
    @RequiresPermissions("act:model:node:setting")
    public ModelAndView nodeSettingView(String menuId,String nodeId,String modelId,String nodeType,ModelAndView modelAndView, HttpServletRequest request){
    	LoginUser user = getLoginUser();
    	Result<Map<String, List<Button>>>  buttonsResult= ucenterApiService.queryUserButtonsWithMenu(user,menuId);
	  	if(buttonsResult.codeSuccess()){
	  		 modelAndView.addObject("buttons", buttonsResult.getData());
	  	}
	    ExtendActNodeset nodesetEntity = nodesetService.queryByNodeId(nodeId);
	    if(nodesetEntity == null){
	    	nodesetEntity = new ExtendActNodeset();
	    	nodesetEntity.setNodeId(nodeId);
	    	nodesetEntity.setModelId(modelId);
	    	nodesetEntity.setNodeType(nodeType);
	    }
	    Map<String,List<Object>> dicts = new HashMap<>();
	    dicts.put("nodeAction", Constant.ActAction.getDictList());
	    dicts.put("useStatus", UseStatus.getDictList());
		modelAndView.addObject("dicts", dicts);
	  	modelAndView.addObject("record", nodesetEntity);
	  	modelAndView.setViewName("activiti/model/node/setting");
        return modelAndView;
    }  
    
    
    /**
     * 保存节点设置
     * @param nodesetEntity 流程节点配置
     * @return
     */
    @RequestMapping(value = "nodeSetting",method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("act:model:node:setting")
    public ResponseEntity<Result<Object>> saveNode(String type,ExtendActNodeset nodesetEntity){
        try {
        	nodesetEntity.setNodeType(type);
            nodesetService.saveNode(nodesetEntity);
            return doSuccess("设置成功!",null);
        } catch (IOException e) {
            log.error(e.getLocalizedMessage());
            return doError("设置失败!");
        }
    }

    
    /**
     * 节点用户设置
     * @param request
     * @return
     */
    @RequestMapping("nodePeopleView")
    @RequiresPermissions("act:model:node:people")
    public ModelAndView nodePeopleView(String menuId,String nodeId,String modelId,ModelAndView modelAndView, HttpServletRequest request){
    	LoginUser user = getLoginUser();
    	Result<Map<String, List<Button>>>  buttonsResult= ucenterApiService.queryUserButtonsWithMenu(user,menuId);
	  	if(buttonsResult.codeSuccess()){
	  		 modelAndView.addObject("buttons", buttonsResult.getData());
	  	}
	  	modelAndView.addObject("nodeId", nodeId);
		modelAndView.addObject("modelId", modelId);
	  	modelAndView.setViewName("activiti/model/node/people");
        return modelAndView;
    }  
    
    
    /**
     * 人员查询
     * @param request
     * @return
     * @throws Exception 
     */
    @SuppressWarnings("unchecked")
	@RequestMapping("peopleQuery")
    @RequiresPermissions("act:model:node:people")
    @ResponseBody
    public ResponseEntity<Map<String,Object>> peopleQuery(HttpServletRequest request) throws Exception{
    	 LoginUser user = getLoginUser();
    	 PageDto<User> pageDto= this.createJQPage(request);
    	 pageDto = ucenterApiService.queryUserList(pageDto,new User(),user);
 		return doSuccess(DataGridUtil.dataConvert(pageDto));
    }
    
    /**
     * 人员查询
     * @param request
     * @return
     * @throws Exception 
     */
    @SuppressWarnings("unchecked")
	@RequestMapping("selectPeopleQuery")
    @RequiresPermissions("act:model:node:people")
    @ResponseBody
    public ResponseEntity<Map<String,Object>> selectPeopleQuery(String nodeId,HttpServletRequest request) throws Exception{
    	// LoginUser user = getLoginUser();
    	 PageDto<User> pageDto= this.createJQPage(request);
    	 List<String> ids  = nodeuserService.queryIds(Constant.SelectType.USER.getValue(),nodeId);
    	 Result<List<User>> result = ucenterApiService.queryUserList(ids);
    	 if(result.codeSuccess()){
    		 pageDto.setRecords(result.getData()); 
    	 }
 		return doSuccess(DataGridUtil.dataConvert(pageDto));
    }
    
    
    /**
     * 新增用户
     * @param modelEntity
     * @return
     */
    @RequestMapping("addUser")
    @ResponseBody
    @RequiresPermissions("act:model:node:people")
    public ResponseEntity<Result<Object>> addUser(String userId,String nodeId){
    	LoginUser user = getLoginUser();
        Result<Object> result = nodeuserService.addUser(userId,nodeId,user);
        if(result.codeSuccess()){
        	return doSuccess(result.getMsg());
        }
        return doError(result.getMsg());
    }
    
    /**
     * 删除用户
     * @param modelEntity
     * @return
     */
    @RequestMapping("deleteUser")
    @ResponseBody
    @RequiresPermissions("act:model:node:people")
    public ResponseEntity<Result<Object>> deleteUser(String userId,String nodeId){
    	LoginUser user = getLoginUser();
        Result<Object> result = nodeuserService.deleteUser(userId,nodeId,user);
        if(result.codeSuccess()){
        	return doSuccess(result.getMsg());
        }
        return doError(result.getMsg());
    }
   
 
    /**
     * 节点角色设置
     * @param request
     * @return
     */
    @RequestMapping("nodeRoleView")
    @RequiresPermissions("act:model:node:role")
    public ModelAndView nodeNodeView(String menuId,String nodeId,String modelId,ModelAndView modelAndView, HttpServletRequest request){
    	LoginUser user = getLoginUser();
    	Result<Map<String, List<Button>>>  buttonsResult= ucenterApiService.queryUserButtonsWithMenu(user,menuId);
	  	if(buttonsResult.codeSuccess()){
	  		 modelAndView.addObject("buttons", buttonsResult.getData());
	  	}
	  	modelAndView.addObject("nodeId", nodeId);
		modelAndView.addObject("modelId", modelId);
	  	modelAndView.setViewName("activiti/model/node/role");
        return modelAndView;
    }  
    
    /**
     * 角色查询
     * @param request
     * @return
     * @throws Exception 
     */
    @SuppressWarnings("unchecked")
	@RequestMapping("roleQuery")
    @RequiresPermissions("act:model:node:role")
    @ResponseBody
    public ResponseEntity<Map<String,Object>> roleQuery(HttpServletRequest request) throws Exception{
    	 LoginUser user = getLoginUser();
    	 PageDto<Role> pageDto= this.createJQPage(request);
    	 pageDto = ucenterApiService.queryRoleList(pageDto,new Role(),user);
 		return doSuccess(DataGridUtil.dataConvert(pageDto));
    }
    
    /**
     * 人员查询
     * @param request
     * @return
     * @throws Exception 
     */
    @SuppressWarnings("unchecked")
	@RequestMapping("selectRoleQuery")
    @RequiresPermissions("act:model:node:role")
    @ResponseBody
    public ResponseEntity<Map<String,Object>> selectRoleQuery(String nodeId,HttpServletRequest request) throws Exception{
    	 //LoginUser user = getLoginUser();
    	 PageDto<Role> pageDto= this.createJQPage(request);
    	 List<String> ids  = nodeuserService.queryIds(Constant.SelectType.ROLE.getValue(),nodeId);
    	 Result<List<Role>> result = ucenterApiService.queryRoleList(ids);
    	 if(result.codeSuccess()){
    		 pageDto.setRecords(result.getData()); 
    	 }
 		return doSuccess(DataGridUtil.dataConvert(pageDto));
    }
    
    /**
     * 新增角色
     * @param modelEntity
     * @return
     */
    @RequestMapping("addRole")
    @ResponseBody
    @RequiresPermissions("act:model:node:people")
    public ResponseEntity<Result<Object>> addRole(String roleId,String nodeId){
    	LoginUser user = getLoginUser();
        Result<Object> result = nodeuserService.addRole(roleId,nodeId,user);
        if(result.codeSuccess()){
        	return doSuccess(result.getMsg());
        }
        return doError(result.getMsg());
    }
    
    /**
     * 删除角色
     * @param modelEntity
     * @return
     */
    @RequestMapping("deleteRole")
    @ResponseBody
    @RequiresPermissions("act:model:node:people")
    public ResponseEntity<Result<Object>> deleteRole(String roleId,String nodeId){
    	LoginUser user = getLoginUser();
        Result<Object> result = nodeuserService.deleteRole(roleId,nodeId,user);
        if(result.codeSuccess()){
        	return doSuccess(result.getMsg());
        }
        return doError(result.getMsg());
    }
    
    
    /**
     * 部署流程
     * @param modelId 模型id
     * @return
     */
    @RequestMapping(value = "build",method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("act:model:build")
    public ResponseEntity<Result<Object>> build(String modelId){
        try {
            extendActModelService.deploy(modelId);
            return doSuccess(); 
        } catch (IOException e) {
            log.error(e.getMessage());
            return doError(e.getMessage());
        }
    }

   
    /******************************************************************/
   


}
